<?php

class Applications extends Controller {

	function Applications()
	{
		parent::Controller();	
        if(!admin_session_check()) redirect('admin/login');
        if(!is_allowed("all")) show_404(); 
        $this->load->model('productsmodel');   
    
	}     
    
    function index()
    {

        $data["list"] = $this->productsmodel->admin_get_all_applications();
        $data["response"] = get_response();        

        $this->load->view('admin/default/head');  
        $this->load->view('admin/default/header', array('selected'=>'products'));  
        $this->load->view("admin/default/nav_products", array('selected' => 'applications')); 
        $this->load->view("admin/default/quick_search");
        $this->load->view('admin/applications/app_list', $data);   
        $this->load->view('admin/default/footer');   

    }
 
    function edit($id = NULL)
    {
                                
        if($id == NULL) show_404();

        $data["item"] = $this->productsmodel->admin_get_application($id); 
        if(empty($data["item"])) show_404();

        //$data["products"] = $this->productsmodel->admin_get_application_products($id); 

        $this->_process_form();

        $data["response"] = get_response(); 
        $data["token"] = generate_token("application",720); 
        $data["action"] = "update";  
        $data["standalone"] = false;

        $this->load->view('admin/default/head');  
        $this->load->view('admin/default/header', array('selected'=>'products'));  
        $this->load->view("admin/default/nav_products", array('selected' => 'applications'));
        $this->load->view("admin/default/quick_search");
        $this->load->view('admin/applications/app_form', $data);   
        $this->load->view('admin/default/footer');   

    }

    function add()
    {
        $this->_process_form();

        $data["item"]['id_Applications'] = "";
        $data["item"]['Name_Applications'] = "";
        $data["item"]['Image_Applications'] = "";

        $data["response"] = get_response();
        $data["token"] = generate_token("application",720); 
        $data["action"] = "create";                                       

        $this->load->view('admin/default/head');          
        $this->load->view('admin/default/header', array('selected'=>'products'));  
        $this->load->view("admin/default/nav_products", array('selected' => 'applications'));
        $this->load->view('admin/applications/app_form', $data);   
        $this->load->view('admin/default/footer');   

    }

    function preview($id = NULL)
    {

        if($this->input->post("submit_action") === FALSE){

            $data["item"] = $this->productsmodel->admin_get_application($id, "id_Applications as id, Name_Applications as title, Image_Applications as image, Active_Applications as active "); 
            if (empty($data["item"])) show_404();             

            $data["action"] = "view";

        } else {

            $data["item"] = array(
                'id' => $this->input->post("id", TRUE),
                'title' => ucfirst($this->input->post("name", TRUE)),
                'image' => $this->input->post("image", TRUE));

            $data["action"] = "preview";

        }

        $data["controller"] = "applications";

        $products = $this->productsmodel->get_products_by_application($id, "products.id_Products, Name_Products AS title, Main_Image AS image, Introduction_Products AS intro");
        $data["grouped_products"] = $this->productsmodel->group_into_categories($products);

        $this->load->view('admin/previews/preview_applications_template', $data);   

    }

    function _process_form()
    {
        $this->load->library("form_validation"); 

        if($this->input->post("submit_action") !== FALSE){
                              
            if ($this->_validate_form()) {
                                
                if (validate_token("application",$this->input->post("token",TRUE))){
                           
                    $data = array(  
                        'Name_Applications' => ucfirst($this->input->post("name", TRUE)),
                        'Image_Applications' => $this->input->post("image", TRUE)
                    );
            
                    switch($this->input->post("submit_action")){    
                                    
                        case 'create':
                                                           
                            $new_id = $this->productsmodel->admin_create_new_application($data);
                            set_response('success','The product Application <i>'.$data['Name_Applications'].'</i> was created. <a href="'.site_url("admin/applications/preview/".$new_id).'" rel=view">Click to view</a>');
                            redirect('admin/applications');

                        break;
                        case 'update':
                                                             
                            $id = $this->input->post("id");
                            $this->productsmodel->admin_update_application($id, $data);
                            set_response('success', "The product Application <i>".$data["Name_Applications"].'</i> was updated. <a href="'.site_url("admin/applications/preview/".$id).'" rel="view">Click to view</a>');
                            redirect('admin/applications');

                        break;        

                    }    
                }
            }

        } else if ($this->input->post("json") !== FALSE){
            
            if ($this->_validate_form()){

                $input_data = array(  
                    'Name_Applications' => ucfirst($this->input->post("name", TRUE)),
                    'Image_Applications' => $this->input->post("image", TRUE)
                );
                $new_id = $this->productsmodel->admin_create_new_application($input_data);
                  
                $data = array(
                    "id" => $new_id,
                    "name" => quotes_to_entities($input_data["Name_Applications"]));
        
                $r = array(
                    'response' => '<span class="success">The product Application <i>'.$data["name"].'</i> was created.</span>',
                    'success' => TRUE,
                    'item' => $data);

            } else {

                $r = array(
                    'response' => validation_errors(),
                    'success' => FALSE);

            }

            echo json_encode($r);   
            die();

        }
    }
//  returns in json format: response:string, success:boolean, [item:array]
    public function create()
    {   

        $this->load->library("form_validation");                     
        $name = ucfirst(strip_tags($this->input->post('name', TRUE)));
        $image = $this->input->post('image', TRUE);

        if($this->_validate_form()){

            $data = array('Name_Applications' => $name);
            $new_id = $this->productsmodel->admin_create_new_application($name, $image);

            $data = array(
                "id" => $new_id,
                "name" => quotes_to_entities($name),
                "image" => $image);
    
            $r = array(
                'response' => '<span class="success">A new application was created</span>',
                'success' => TRUE,
                'item' => $data);

        } else {

            $r = array(
                'response' => validation_errors(),
                'success' => FALSE);

        }

        echo json_encode($r);   
    }  


    function remove($id = false){

        if($id == NULL) show_404();
        $data["item"] = $this->productsmodel->admin_get_application($id, "id_Applications as id, Name_Applications as title, Image_Applications as image, Active_Applications as active ");  

        if(empty($data["item"])){
            set_response('error', "The product application you're attempting to delete does not exist");
            redirect('admin/applications');
        } else {
            $products = $this->productsmodel->get_products_by_application($id, "products.id_Products, Name_Products AS title, Main_Image AS image, Introduction_Products AS intro");
            $data["grouped_products"] = $this->productsmodel->group_into_categories($products);
            
            $this->load->view('admin/default/head');  
            $this->load->view('admin/default/header', array('selected'=>'products'));  
            $this->load->view("admin/default/nav_products", array('selected' => 'applications'));
            $this->load->view("admin/default/quick_search");
            $this->load->view('admin/applications/app_delete', $data);   
            $this->load->view('admin/default/footer'); 
        }

    }
    function confirm_removal($id = false){

        if($id == NULL) show_404();  

        $data["item"] = $this->productsmodel->admin_get_application($id);

        if(empty($data["item"])){
            set_response('error', "The product application you're attempting to delete does not exist");
            redirect('admin/applications');
        } 

        $this->productsmodel->admin_delete_application($id);
        $this->productsmodel->admin_delete_application_products($id);
        set_response('success', "The product Application <i>".$data["item"]["Name_Applications"]."</i> was deleted.");
        redirect('admin/applications');
    }

    function deactivate($id = false){

        if($id == NULL) show_404();  
        $data = array('Active_Applications' => 0);
        $this->productsmodel->admin_update_application($id, $data);
        $item = $this->productsmodel->admin_get_application($id);
        set_response('success', "The application <i>".$item["Name_Applications"].'</i> is now inactive. <a href="'.site_url("admin/applications/preview/".$id).'" rel="view">Click to view</a>');
        redirect('admin/applications');
    }
    function activate($id = false){

        if($id == NULL) show_404();  
        $data = array('Active_Applications' => 1);
        $this->productsmodel->admin_update_application($id, $data);  
        $item = $this->productsmodel->admin_get_application($id);
        set_response('success', "The application <i>".$item["Name_Applications"].'</i> is now active. <a href="'.site_url("admin/applications/preview/".$id).'" rel="view">Click to view</a>');
        redirect('admin/applications');
    }
    

    private function _validate_form(){
                             
        $config = array(
                        array(
                         'field'   => 'name',
                         'label'   => 'Name',
                         'rules'   => 'trim|xss_clean|required|max_length[80]|callback_check_duplicated'
                        ),
                        array(
                         'field'   => 'image',
                         'label'   => 'Image',
                         'rules'   => 'trim|xss_clean|required'
                        )
                    );
        
                                                 
        $this->form_validation->set_rules($config);       
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        
        if ($this->form_validation->run($this) == FALSE){
            return FALSE;
        }else
            return TRUE;

    }

     public function check_duplicated($name){ 

        $id = $this->input->post("id");

        if($this->productsmodel->is_duplicated('applications','Name_Applications',$name,'id_Applications',$id)){
            $this->form_validation->set_message('check_duplicated', "An application with that name already exists");
            return FALSE;
        }else{
            return TRUE;    
        }
    } 

}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */